<template>
  <div class="app-container">
    <el-select filterable v-model="listQuery.status" placeholder="请选择管理员状态">
      <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-input v-model="listQuery.role_id" placeholder="请输入管理员角色编号" style="width:200px" clearable></el-input>
    <el-input v-model="listQuery.search" placeholder="请输入管理员账号" style="width:200px" clearable></el-input>
    <el-button type="primary" @click="getList" icon="el-icon-search"  >搜索</el-button>

<!--    <div class="filter-container" style="margin-top:10px;">-->
      <el-button   class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate()">
        添加
      </el-button>
<!--    </div>-->

    <el-table :data="menuList" style="margin-bottom: 20px;margin-top: 10px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="admin_id" label="账户id" > </el-table-column>
      <el-table-column prop="admin_account" label="账户" > </el-table-column>
      <el-table-column prop="admin_name" label="昵称" > </el-table-column>
      <el-table-column prop="avatar" label="头像" >
        <template slot-scope="scope">
          <el-popover placement="right" width="400" trigger="hover">
            <img :src="scope.row.avatar" alt="" style="max-width: 400px;max-height: 400px">
            <img slot="reference" :src="scope.row.avatar" alt="" style="width: 50px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="email" > </el-table-column>
      <el-table-column prop="last_login_ip" label="最后登陆ip" > </el-table-column>
      <el-table-column prop="last_login_time" label="最后登陆时间" > </el-table-column>
      <el-table-column prop="login_count" label="登陆次数" > </el-table-column>
      <el-table-column prop="phone" label="电话" > </el-table-column>
      <el-table-column prop="role" label="权限" > </el-table-column>
      <el-table-column prop="add_time" label="添加时间" > </el-table-column>
      <el-table-column prop="status" label="状态" >
        <template slot-scope="scope">
          {{ scope.row.status === 1 ?'正常':'' }}
          {{ scope.row.status === 2 ?'删除或离职':'' }}
        </template>
      </el-table-column>
<!--      <el-table-column min-width="280" label="操作">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>-->
<!--            编辑-->
<!--          </el-button>-->
<!--&lt;!&ndash;          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <cus-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage" @pagination="getList"/>


    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="管理员真实姓名" :prop="dialogStatus === 'create'?'admin_name':''">
          <el-input v-model="form.admin_name" placeholder="请输入管理员真实姓名" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label='管理员登录账号' prop="admin_account">
          <el-input v-model="form.admin_account" placeholder="管理员登录账号(仅限英文)" maxlength="50" show-word-limit onkeyup="value = value.replace(/[^a-zA-Z]/g,'')"/>
        </el-form-item>
        <el-form-item label='密码' :prop="dialogStatus === 'create'?'password':''">
          <el-input v-model="form.password" placeholder="请输入密码"  show-password/>
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'create'" label="角色编号" prop="role_id">
          <el-select filterable v-model="form.role_id" placeholder="请选择角色编号" style="width:280px;">
            <el-option v-for="item in sociatyData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='邮箱'>
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label='管理员头像'>
          <span>{{form.avatar?form.avatar.name:''}}</span>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { permissionMenu, saveMenu, deleteMenu,  updateMenu, sociatyList } from '@/api/system/admin'
  import md5 from 'js-md5'
  import treeTable from '@/components/TreeTable'
  import { validateCh } from '@/utils/validate'

  // 常量title
  const tempDesc = {
    'id': '',
    'parentId': '',
    'menu_key': '菜单key值',
    'menu_name': '名称',
    'level': '排序',
    'icon': '图标',
    'type': '类型',
    'status': '状态',
    'parentName': '上级菜单'
  }

  export default {
    components: { treeTable },
    data() {
      const _validateCh = (rule, value, callback) => {
        if (!!value && validateCh(value)) {
          callback(new Error('不能包含中文'))
        }
        callback()
      }
      return {
        imageUrl: '',
        expandAll: false,
        // expandAll: true, // 是否全部展开
        expandAllTitle: '展开全部',
        tempDesc: tempDesc,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          perPage: 10
        },
        defaultProps: {
          children: 'children',
          label: 'menu_name'
        },
        columns: [
          {
            label: '菜单名称',
            key: 'title',
            width: 220,
            expand: true,
            align: 'left',
            headerAlign: 'center'
          },
          {
            label: '菜单key值',
            key: 'menu_key'
          },
          {
            label: tempDesc.type,
            key: 'type'
          },
          {
            label: '状态',
            key: 'status'
          },
          {
            label: tempDesc.icon,
            key: 'icon'
          },
          {
            label: '菜单层级',
            key: 'level'
          }
        ],
        menuList: [],
        menuTree: [],// 树形菜单
        menuListData: [],// 树形菜单
        dialogFormVisible: false,
        dialogStatus: '',
        titleMap: {
          update: '编辑',
          create: '增加'
        },
        optionsStatus: [{value:undefined,label: '全部管理员状态'},{value: '1',label: '正常'},{value: '2',label: '删除或离职'}],
        sociatyData:[],
        form: {
          admin_name: undefined,
          admin_account: undefined,
          password: undefined,
          role_id: undefined,
          email: undefined,
          phone: undefined,
          avatar: undefined,
        },
        rules: {
          admin_name: [
            { required: true, message: '请输入管理员真实姓名', trigger: 'blur' }
          ],
          admin_account: [
            { required: true, message: '请输入管理员登录账号', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          role_id: [
            { required: true, message: '请输入角色编号', trigger: 'blur' }
          ],
        }
      }
    },
    created() {
      if (this.global_checkBtnPermission(['sys:menu:add', 'sys:menu:addsub', 'sys:menu:edit', 'sys:menu:delete'])) {
        this.columns.push({ label: '操作', key: 'operation', width: 320 })
      }
      this.getList()
      this.sociatyList()
    },
    methods: {
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        this.form.avatar = file
      },
      getList() {
        this.listLoading = true
        let urlData = '?';
        if(this.listQuery.page){ urlData = urlData + `page=${this.listQuery.page}&`}
        if(this.listQuery.perPage){ urlData = urlData + `perPage=${this.listQuery.perPage}`}
        if(this.listQuery.status){ urlData = urlData + `&status=${this.listQuery.status}`}
        if(this.listQuery.role_id){ urlData = urlData + `&role_id=${this.listQuery.role_id}`}
        if(this.listQuery.search){ urlData = urlData + `&search=${this.listQuery.search}`}

        permissionMenu(urlData).then(response => {
          this.menuList = response.data.list
          this.total = response.data.meta.total;

          this.listLoading = false
        })
      },
      sociatyList() {
        sociatyList().then(response => {
          let sociatyListData = response.data
          let obg = new Object()
          let obgArr = []
          for(let i in sociatyListData){
            obg['id'] = i;
            obg['name'] = sociatyListData[i]
            obgArr.push(obg)
          }
          this.sociatyData = obgArr
        })
      },
      handleNodeClick(data) {
        this.form.menu_id = data.menu_id
      },
      handleCreate(row) {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleUpdate(row) {
        this.form = []
        this.form.admin_name= row.admin_name
          // this.form.admin_account= row.admin_account
          this.form.password= row.password
          // this.form.role_id= row.role_id
          this.form.email= row.email
          this.form.phone= row.phone
          this.form.avatar= row.avatar

        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        let parentNode = this.findTreeNode(row.parentId)
        if (parentNode) {
          this.form.parentName = parentNode.menu_name
        }

        this.form = Object.assign({}, this.form)
      },
      handleDelete(row) {
        deleteMenu(row.id).then(response => {
          if (response.code === 0) {
            this.getList()
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
          }
        })
      },
      submitForm() {
        // this.form.parentName = undefined;
        this.$refs['dataForm'].validate(valid => {
          if (valid && this.dialogStatus === 'create') {
            // let md5PW = md5(this.form.password)
            // this.form.password = md5PW
            let newForm = {
              admin_name: this.form.admin_name,
              admin_account:this.form.admin_account,
              password: md5(this.form.password),
              role_id: this.form.role_id,
              email: this.form.email,
              phone: this.form.phone,
              avatar: this.form.avatar,
            }
            let formData = new FormData();
            for(let item in newForm){newForm[item] === undefined? '':formData.append(item, newForm[item]);}
            saveMenu(formData).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
          }else if(valid && this.dialogStatus === 'update'){
            let formData = new FormData();
            for(let item in this.form){this.form[item] === undefined? '':formData.append(item, this.form[item]);}
            updateMenu(this.form).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
          }
        })
      },
      findTreeNode(id) {
        let node = this._.find(this.menuList, { id: parseInt(id) })
        return node
      },
      handleExpand() {
        this.expandAll = !this.expandAll
        this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
      },
      resetForm() {
        this.form = {
          admin_name: undefined,
          admin_account: undefined,
          password: undefined,
          role_id: undefined,
          email: undefined,
          phone: undefined,
          avatar: undefined,
        }
      },
      // 监听dialog关闭时的处理事件
      handleDialogClose() {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
        }
      }
    }
  }
</script>
